package studio.xiaoyun.core.parameter.criterion;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import studio.xiaoyun.core.exception.CoreException;
import studio.xiaoyun.core.parameter.Parameter;

public class CriterionEquals extends Criterion {
	private static final long serialVersionUID = -3797578290187968374L;
	private String propertyName;
	private Object value;

	protected CriterionEquals(String propertyName, Object value) {
		this.propertyName = propertyName;
		this.value = value;
	}

	@Override
	public List<String> getPropertyName() {
		return Arrays.asList(propertyName);
	}

	@Override
	public String getQuery(Parameter parameter) {
		StringBuffer result = new StringBuffer();
		DataType dataType = this.getDataType(parameter, propertyName);
		switch (dataType) {
		case DATE:
			result.append("%s = '");
			if (value instanceof Date) {
				result.append(this.formatDate((Date) value));
			} else {
				result.append(value.toString());
			}
			result.append("'");
			break;
		case NUMBER:
			result.append("%s = ").append(value.toString());
			break;
		case STRING:
			result.append("%s = '").append(value.toString()).append("'");
			break;
		case ENUM:
			Object obj = value;
			Object objValue = null;
			if(!value.getClass().isEnum()){
				Class<?> type = this.getFieldByName(parameter, propertyName).getType();
				try{
					Method method = type.getMethod("valueOf", String.class);
					obj = method.invoke(null, value.toString());
				}catch(Exception e){
					throw new CoreException(type.getName()+"中没有定义"+value.toString());
				}
			}
			try{
				objValue = obj.getClass().getMethod("value").invoke(obj);
			}catch(Exception e){
				objValue = obj.toString();
			}
			if(objValue.getClass() == Integer.TYPE || objValue.getClass() == Integer.class){
				result.append("%s = ").append(objValue.toString());
			}else{
				result.append("%s = '").append(objValue.toString()).append("'");
			}
			break;
		default:
			throw new CoreException("属性" + propertyName + "不支持equals");
		}
		return result.toString();
	}

}
